package com.sixmac.controller;

import com.google.common.base.Strings;
import com.sixmac.annotation.AuthUser;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.module.*;
import com.sixmac.platform.service.RoomService;
import com.sixmac.util.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by admin on 2018/9/4.
 */
@Controller
@RequestMapping("/mine")
@ResponseBody
public class MineController extends BaseController {
    @Autowired
    RoomService roomService;
    @Autowired
    WeChatConfig weChatConfig;
    /**
     * @api {post} /mine/index 0.1用户资料
     * @apiName mine.index
     * @apiGroup mine
     * @apiParam {String} token token
     * @apiSuccess {String} phone 手机号码
     * @apiSuccess {String} name 房东名称
     * @apiSuccess {String} sex 性别 1男2女
     * @apiSuccess {String} birth 出生日期 比如（2018-09-03）
     * @apiSuccess {String} idCard 身份证号码
     * @apiSuccess {String} idCardFront 身份证正面
     * @apiSuccess {String} idCardReverse 身份证反面
     */
    @AuthUser
    @RequestMapping("/index")
    public AjaxResult index(Tenant tenant) {
        return json(getData("tenant", Blade.create(Tenant.class).findById(tenant.getId())));
    }

    /**
     * @api {post} /mine/editUser 0.2编辑用户（提交个人信息资料）
     * @apiName mine.editUser
     * @apiGroup mine
     * @apiParam {String} token token
     * @apiParam {String} phone 手机号码
     * @apiParam {String} name 房东名称
     * @apiParam {String} sex 性别 1男2女
     * @apiParam {String} birth 出生日期 比如（2018-09-03）
     * @apiParam {String} idCard 身份证号码
     * @apiParam {String} idCardFront 身份证正面
     * @apiParam {String} idCardReverse 身份证反面
     * @apiParam {String} handCard 手持身份证
     */
    @AuthUser
    @RequestMapping("/editUser")
    public AjaxResult editUser(Tenant tenant, String phone, String name, Integer sex, String birth, String idCard,String handCard, String idCardFront, String idCardReverse) {
        Tenant t = new Tenant();
        t.setId(tenant.getId());
        t.setName(name);
        if (!Strings.isNullOrEmpty(phone)) {
            if (Blade.create(Tenant.class).findFirstBy("mobile=#{mobile}", getData("mobile", phone)) != null)
                return error("手机号码已经存在");
            t.setMobile(phone);
        }
        t.setSex(sex);
        if (!Strings.isNullOrEmpty(birth)) {
            t.setBirthday(DateKit.parse(birth, "yyyy-MM-dd"));
        }
        if (!Strings.isNullOrEmpty(idCard)) {
            if (Blade.create(Tenant.class).findFirstBy("idCard=#{idCard} and id!="+tenant.getId(), getData("idCard", idCard)) != null)
                return error("身份证号码已经存在");
            t.setIdCard(idCard);
        }
        t.setIdCardFront(idCardFront);
        t.setIdCardReverse(idCardReverse);
        if (!Strings.isNullOrEmpty(handCard)) {
            t.setHandCard(handCard);
        }
        boolean f = Blade.create(Tenant.class).update(t);
        if (f)
            return success("");
        return error("错误");
    }


    /**
     * @api {post} /mine/getStatus 获取用户状态 inStatus 入住状态 0未入住1已入住 approve 0未申请 1已申请 auth 1资料已完善0未完善 live 1受理中 0可申请
     * @apiName mine.index
     * @apiGroup mine
     * @apiParam {String} token token
     */
    @AuthUser
    @RequestMapping("/getStatus")
    public AjaxResult getStatus(Tenant tenant) {
        tenant = Blade.create(Tenant.class).findById(tenant.getId());
        if(tenant==null){
            return new AjaxResult().addError("关掉小程序重试").setCode(8);
        }
        HashMap<String,Object> data = new HashMap<>();
        boolean result = true;
        if (tenant.getName()==null||tenant.getName().length() == 0){
            result = false;
        }

        if (tenant.getMobile()==null||tenant.getMobile().length() == 0){
            result = false;
        }

        if (tenant.getIdCard()==null||tenant.getIdCard().length() == 0){
            result = false;
        }

        if (tenant.getIdCardFront()==null||tenant.getIdCardFront().length() == 0){
            result = false;
        }

        if (tenant.getIdCardReverse()==null||tenant.getIdCardReverse().length() == 0){
            result = false;
        }

        if (tenant.getHandCard()==null||tenant.getHandCard().length() == 0){
            result = false;
        }
        data.put("auth",result?1:0);


        TenantLive tenantLive = Blade.create(TenantLive.class).findFirstBy(" tenantId="+tenant.getId()+" and status=1",null);

        data.put("live",0);//居住证可以申请
        if (tenantLive != null){
            data.put("live",1);
        }

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+tenant.getId(),null);

        data.put("defence",0);//布防
        if (tenantRoom != null){
            if (tenantRoom.getDefence()!=null&&tenantRoom.getDefence()==1){
                data.put("defence",1);//布防
            }
        }


        data.put("isApply",1);
        if (tenantRoom!=null){
            tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" (isAdmin = 2 or isAdmin = 1) and roomId = "+tenantRoom.getRoomId()+" and status = 1 ",null);
            if (tenantRoom!=null){
                data.put("isApply",1);
            }else{
                data.put("isApply",0);
            }
        }

        tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" status = 1 and tenantId ="+tenant.getId(),null);
        data.put("isAdmin",0);
        if (tenantRoom!=null&&tenantRoom.getIsAdmin()!=null&&tenantRoom.getIsAdmin()==2){
            data.put("isAdmin",1);
        }

        if (tenantRoom!=null&&tenantRoom.getFingerprint()!=null){
            HashMap map = new HashMap();
            map.put("fingerprintNum",tenantRoom.getFingerprint());
            map.put("startTime",tenantRoom.getLockStartTime());
            map.put("endTime",tenantRoom.getLockEndTime());
            data.put("fingerprint",map);
        }

        if (tenantRoom!=null){
            Pay pay = Blade.create(Pay.class).findFirstBy(" isDo = 0 and status = 1 and tenantId="+tenant.getId()+" and trId ="+tenantRoom.getId(),null);
            if(pay!=null){
                TenantRoom tenantRoom2 = Blade.create(TenantRoom.class).findById(pay.getTrId());
                DayMoney dayMoney = Blade.create(DayMoney.class).findById(pay.getDayId());
                pay.setStartTime(tenantRoom2.getLockStartTime());
                pay.setEndTime(DateKit.getAfterDayDate(tenantRoom2.getLockEndTime(),dayMoney.getDay()));
                data.put("pay",pay);
            }
        }

        data.put("inStatus",0);
        if (tenantRoom!=null){
            Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());
            data.put("electric",room==null||room.getElectric()==null?"100":room.getElectric());
            Contract concat = Blade.create(Contract.class).findFirstBy(" tenantRoomId="+tenantRoom.getId(),null);
            Landlord landlord = Blade.create(Landlord.class).findById(room.getLandlordId());
            data.put("inStatus",1);
            data.put("contact",concat);
            data.put("room",room);
            data.put("landlord",landlord);
            return json(data);
        }

        tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" approve = 3 and tenantId ="+tenant.getId(),null);
        data.put("approve",0);
        if (tenantRoom!=null){
            data.put("approve",1);
            return json(data);
        }

        return json(data);
    }

}
